<template>
  <div>
    <common-header title="搜索"></common-header>
    <div class="headerWrap">
      <van-search
        v-model="keyWord"
        show-action
        placeholder="搜索商品、品牌"
        @search="onSearch"
      >
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>
      <div class="divideBg"></div>
      <div class="history" v-if="history.length">
        <p>历史记录</p>
        <ul class="goodul">
          <li  v-for="his in history" :key="his" @click="toOwnList(his)"> {{his}} </li>
        </ul>
      </div>
      <div class="noHistory" v-if="!history.length">
        <p>暂无历史记录</p>
      </div>
    </div>
  </div>
</template>

<script>
import CommonHeader from '@components/CommonHeader'
import { getList } from '@api'
export default {
  data () {
    return {
      keyWord: '',
      history: localStorage.getItem('history') ? JSON.parse(localStorage.getItem('history')) : [] // 存取历史记录
    }
  },
  methods: {
    onSearch () {
      // 将输入的内容添加到历史记录中
      this.history.unshift(this.keyWord)
      // 去重
      this.history = [...new Set(this.history)]
      // 将数据存到本地中
      localStorage.setItem('history', JSON.stringify(this.history)) // 存入本地需要存字符串
      this.$router.push({
        path: '/searchList',
        query: {
          key: this.keyWord
        }
      })
    },
    toOwnList (item) {
      getList({
        nameLike: item,
        orderBy: this.orderBy
      }).then(res => {
        this.lists = res.data.data
        this.$router.push({
          path: '/searchList',
          query: {
            key: item
          }
        })
      })
    }
  },
  components: {
    CommonHeader
  }
}
</script>

<style lang="scss" scoped>
.history {
  min-height: 150px;
  box-sizing: border-box;
  p {
    font-size: 14PX;
    color:#b0b0b0;
    font-weight: 700;
    padding-top: 10px;
    padding-left: 5px;
  }
  .goodul {
    display: flex;
    flex-wrap: wrap;
    li {
      padding: 10px;
      border: 1px solid #e0e0e0;
      margin: 5px;
      color: #000;
      font-size: 12PX;
    }
  }
}
.noHistory {
  min-height: 150px;
  box-sizing: border-box;
  text-align: center;
  p {
    font-size: 16PX;
    padding-top: 20px;
  }
}
</style>
